package com.zjl.spring.config;

import com.zjl.spring.common.Response;
import com.zjl.spring.exception.BaseBizException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/*
 * 全局异常处理
 *
 * @Author zhuangjl
 * @Date 2021/11/11 16:00
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     *
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BaseBizException.class)
    public Object allBusinessExceptionHandler(BaseBizException exception) {
        String errCode = exception.getBaseCode().getCode();
        String errMsg = StringUtils.isNotBlank(exception.getMessage()) ?
                exception.getMessage() : exception.getBaseCode().getDesc();
        LOG.error(errMsg, exception);
        return Response.buildFailure(errCode, errMsg);
    }


}
